var editAlbumIndex;
var albumListApp;
$(document).ready(function () {
    // divWidth('swiperWrapper')
    albumListApp = new Vue({
        el: '#albumListId',
        data: {
            albumList: [],
            imgList: [],
            remarkList: [],
            activePhoto: 0,
            activePhotoInfo: {}
        },
        created: function () {
            this.initAlbum();
            showStorage();
        },
        mounted () {
            window.initAlbum = this.initAlbum; // 方法赋值给window
        },
        methods: {
            initAlbum: function () {
                if($("#begin").val()!=""||$("#end").val()!=""||$("#address").val()!=""){
                    $(".photoListWrapper").hide();
                    $(".photoShowGallery").show();
                    var beginDate=new Date($("#begin").val().replace("-", "/").replace("-", "/"));
                    var endDate=new Date($("#end").val().replace("-", "/").replace("-", "/"));
                    if($("#begin").val()!=""||$("#end").val()!=""){
                        if (beginDate < endDate){
                            initAlbumImg($("#begin").val(), $("#end").val(),$("#address").val());
                        }else{
                            $("#begin").val("")
                            $("#end").val("")
                            layer.msg("日期范围错误，请重输！");
                        }
                    }else{
                        initAlbumImg($("#begin").val(), $("#end").val(),$("#address").val());
                    }
                }else{
                    $(".photoListWrapper").show();
                    $(".photoShowGallery").hide()
                    initAjax($("#address").val(),$("#begin").val(), $("#end").val())
                }
            },
            showPhotoDetail: function (index) {
                showPhotoDetail(index);
            },
            // 选择照片，防止事件冒泡
            handleSelectIcon: function (index) {
                handleSelectIcon(index);
            },
            clickReply: function (remarkInfo) {
                clickReply(remarkInfo);
            },
            updatePhotoCount: function (fileid) {
                updatePhotoCount(fileid)
            },



            photoListEnter: function (param) {
                this.albumList[param].isShow = true;
            },
            photoListLeave: function (param) {
                this.albumList[param].isShow = false;
            },
            editAlbumClick: function (album, indexAlbum) {
                console.log(album.address)
                editAlbumIndex = layer.open({
                    title: "编辑相册",
                    type: 2,
                    area: ['700px', '450px'],
                    fixed: false, //不固定
                    maxmin: true,
                    btn: ['确定', '取消'],
                    content: "editAlbum.html?albumId=" + album.albumId + "&albumName=" + album.albumName + "&albumintro=" + album.albumintro + "&albumpower=" + album.albumpower+ "&address=" + album.address,
                    yes: function (index, layero) {

                        var iframeWin = window[layero.find('iframe')[0].name];
                        iframeWin.saveEditAlbumInfo(indexAlbum);
                    },
                    btn2: function (index, layero) {
                        layer.close(index);
                    },
                    cancel: function () {
                        //右上角关闭回调

                        //return false 开启该代码可禁止点击该按钮关闭
                    }
                });
            },
            deleteAlbumClick: function (album, indexAlbum) {
                $.ajax({
                    data: {
                        albumid: album.albumId
                    },
                    url: "/album/deleteAlbum",
                    dataType: "json",
                    type: "POST",
                    success: function (result) {
                        if (result.success) {
                            window.location.reload()
                        } else {
                            layer.msg("请登录后查看相册", {icon: 2})
                        }
                    },
                    error: function (result) {
                        layer.msg("系统繁忙", {icon: 2})
                    }
                });
            }
        }
    });
    //弹出层
    layui.use('layer', function () {
        var $ = layui.jquery, layer = layui.layer;

        $('.deleteButton').on('click', function () {
            var othis = $(this), method = othis.data('method');
            active[method] ? active[method].call(this, othis) : '';
        });
        //触发事件
        var active = {
            offset: function (othis) {
                var type = othis.data('type'),
                    text = "确认删除吗？",
                    albumId = othis.data('id'),
                    albumIndex = othis.data('index');
                layer.open({
                    type: 1, offset: type,
                    id: 'layerDemo' + type,
                    content: '<div style="padding: 20px 100px;">' + text + '</div>',
                    btn: ['确认', '取消'],
                    btnAlign: 'c',
                    shade: 0,
                    yes: function () {
                        layer.closeAll();
                        deleteAlbum(albumId, albumIndex);
                    }
                });
            },
            confirmTrans: function () {
                layer.msg('已删除', {
                    time: 2000
                });
            }
        };
    });

    //url解码
    var thisURL = document.URL;
    var getval = decodeURI(thisURL).split('?')[1].split("&");
    //url参数转换为键值对
    for (var i = 0; i < getval.length; i++) {
        var albuminfokey = getval[i].split("=")[0];
        var albuminfovalue = getval[i].split("=")[1];
        albuminfo[albuminfokey] = albuminfovalue;
    }
    //相册名称、权限赋值
    $(".albumName").text(albuminfo.albumName);
    $(".albumName").attr("title", albuminfo.albumName);
    if (albuminfo.albumpower == 0) {
        $(".albumPower").text("对外不可见");
    }
    if (albuminfo.albumpower == 1) {
        $(".albumPower").text("对外可见");
    }

    //照片列表获取
    albumId = albuminfo.albumId;

    albumObj.albumid = albumId;
    if (albumId.indexOf("#") != -1) {
        albumId = albumId.substring(0, albumId.indexOf("#"));
    }

    // 监听上传照片按钮
    $(document).on("click", "#uploadImg", function () {
        albuminfo.imageCount = $(".ma5-gallery figure").length;
        location.href = "uploadImg.html?albumId=" + albuminfo.albumId + "&albumName=" + albuminfo.albumName + "&albumpower=" + albuminfo.albumpower;
        localStorage.setItem("imageCount", albuminfo.imageCount);
    })
    // localStorage.setItem("albumId", albuminfo.albumId);

    //监听编辑按钮
    $(document).on("click", "#editImg", function () {
        if ($("#editImg").hasClass("layui-btn-disabled") == false) {   //批量删除按钮禁用
            $("#editImg").removeClass("layui-btn-normal").addClass("layui-btn-disabled");
        }
        $("#sureDelete").css("display", "inline-block"); //确认删除按钮显示
        $("#cancelEdit").css("display", "inline-block"); //取消删除按钮显示
        $("#selectAll").css("display", "inline-block"); //全选按钮显示
        $(".maskImg").css("display", "block");   //照片遮罩显示
        $(".selectIcon").css("display", "block");    //选中框显示
    })
    //监听全选按钮
    $(document).on("click", "#selectAll", function () {
        if ($(this).hasClass("cancelSelectAll") == true) {
            $(".selectIcon").text("");
            $(".selectIcon").removeClass("selected");
            $(this).text("全选");
            $(this).removeClass("cancelSelectAll");
        } else {
            $(".selectIcon").text("√");
            $(".selectIcon").addClass("selected");
            $(this).text("取消全选");
            $(this).addClass("cancelSelectAll");
        }
    })

    $("#meihua").click(function () {
        if (!flag) {
            $(".photoList li").addClass("frame")
            flag = true
            $("#meihua").html("取消美化")
        } else {
            flag = false
            $(".photoList li").removeClass("frame")
            $("#meihua").html("美化照片")
        }

    })

    //监听确认删除按钮
    $(document).on("click", "#sureDelete", function () {
        if ($(".selected").length == 0) {
            alert("请选择照片");
        } else {
            //获取已选择照片的id
            var imageids = [];
            var selectedImage = $(".selected");
            for (var i = 0; i < selectedImage.length; i++) {
                imageids.push(selectedImage[i].getAttribute("id"));
            }

            // 测试接口
            $.ajax({
                data: {
                    imageids: JSON.stringify(imageids)
                },
                url: "/filetransfer/deleteimagebyids",
                dataType: "json",
                type: "POST",
                async: true,
                success: function (result) {
                    if (result.success) {
                        layer.msg("删除成功", {icon: 1});
                        if ($("#editImg").hasClass("layui-btn-disabled") == true) {
                            $("#editImg").removeClass("layui-btn-disabled").addClass("layui-btn-normal");
                        }
                        $(".selectIcon").css("display", "none");
                        $("#selectAll").css("display", "none");
                        $(".maskImg").css("display", "none");
                        $("#sureDelete").css("display", "none");
                        $("#cancelEdit").css("display", "none");
                        //删除photoList中的数组元素
                        for (var j = 0; j < imageids.length; j++) {
                            for (var k = 0; k < albumListApp.imgList.length; k++) {
                                if (imageids[j] == albumListApp.imgList[k].imageid) {
                                    albumListApp.imgList.splice(k, 1);
                                    break;
                                }
                            }
                        }
                        // $(".selected").parent().parent().remove();
                        $(".photoCount").text(albumListApp.imgList.length + "张 /");
                        if (albumListApp.imgList.length == 0) {
                            $(".photoShowGallery").html("<span class='emptyAlbum'>相册为空</span>");
                            $(".photoCount").text("0张 /");
                            $("#editImg").css("display", "none");
                        }
                        initAlbum()
                    } else {
                        layer.msg(result.errorMessage, {icon: 2});
                    }
                },
                error: function () {
                    //alert("系统繁忙!");
                }
            });
        }
    })
    //监听取消编辑按钮
    $(document).on("click", "#cancelEdit", function () {
        $(this).css("display", "none");
        if ($("#editImg").hasClass("layui-btn-disabled") == true) {
            $("#editImg").removeClass("layui-btn-disabled").addClass("layui-btn-normal");
        }
        $(".selectIcon").css("display", "none");
        $(".maskImg").css("display", "none");
        $("#selectAll").css("display", "none");
        $("#sureDelete").css("display", "none");

        $(".selectIcon").text("");
        $(".selectIcon").removeClass("selected");
        $("#selectAll").text("全选");
        $("#selectAll").removeClass("cancelSelectAll");
    })

    // 获取用户头像
    function getUserHeadImg() {
        var userHeadImgUrl = $("#head-nav-img").attr("src");
        $(".userHeadImg").attr("src", userHeadImgUrl);
    }
});

// $(document).keydown(function (event) {
//     if (event.keyCode == 13) {
//         // showStorage()
//         albumListApp.initAlbum()
//     }
// });

function showStorage() {
    $.ajax({
        url: "/filetransfer/getstorage",
        dataType: "json",
        type: "POST",
        success: function (result) {
            if (result.success) {
                $("#storageid").text((result.data.storagesize / (1024 * 1024)).toFixed(2));
            } else {
                layer.msg("请登录后查看相册", {icon: 2})
            }
        },
        error: function (result) {
            //alert("系统繁忙!");
        }
    });
}

function initAjax(address,begin, end) {
    $.ajax({
        url: "/album/getMyAlbumlist",
        data: {
            address: address,
            begin: begin,
            end: end
        },
        dataType: "json",
        type: "POST",
        success: function (result) {
            if (result.success) {
                var dataArr = [];
                var data = result.data.albumList;
                var html = "<ul>"
                for (var i = 0; i < data.length; i++) {
                    var dataMap = {
                        imageUrl: (data[i].fileBeanList.length <= 1) ? "image/picNone.png" : (data[i].fileBeanList[0].fileurl == null ? data[i].fileBeanList[1].fileurl : data[i].fileBeanList[0].fileurl),
                        albumId: data[i].albumid,
                        imageCount: data[i].fileBeanList.length - 1,
                        albumName: data[i].albumname,
                        showAlbumUrl: "showAlbum.html?albumId=" + data[i].albumid + "&albumName=" + data[i].albumname +
                            "&albumpower=" + data[i].albumpower + "&begin=" + result.data.begin + "&end=" + result.data.end,
                        myShowAlbumUrl: "myShowAlbum.html?albumId=" + data[i].albumid + "&albumName=" + data[i].albumname +
                            "&albumpower=" + data[i].albumpower + "&begin=" + result.data.begin + "&end=" + result.data.end,
                        // editAlbumUrl: "editAlbum.html?albumId=" + data[i].albumid+"&albumName="+data[i].albumname+
                        //         "&albumintro="+data[i].albumintro+"&albumpower="+data[i].albumpower,
                        albumintro: data[i].albumintro,
                        address: data[i].address,
                        isShow: false,
                        albumpower: data[i].albumpower
                    };
                    dataArr.push(dataMap);
                }
                albumListApp.albumList = dataArr;
            } else {
                layer.msg("请登录后查看相册", {icon: 2})
            }
        },
        error: function (result) {
            //alert("系统繁忙!");
        }
    });
}

function deleteAlbum(albumId, albumIndex) {
    var albumData = {
        albumid: albumId
    };
    $.ajax({
        data: albumData,
        url: "/album/deletealbum",
        dataType: "json",
        type: "POST",
        success: function (result) {
            if (result.success) {
                albumListApp.albumList.splice(albumIndex, 1);
            } else {
                layer.msg("请登录后查看相册", {icon: 2})
            }
        },
        error: function (result) {
            layer.msg("系统繁忙", {icon: 2})
        }
    });
}

function findAlbum() {
    initAlbum();
}


var albumId;
var albuminfo = {};
var albumObj = {};
var flag = false
function initAlbumImg(begin, end,address) {
    $.ajax({
        url: "/file/getimagelistbyalbum",
        dataType: "json",
        data: {
            begin: begin,
            end: end,
            address:address,
            albumid: albumObj.albumid
        },
        type: "POST",
        success: function (result) {
            console.log(1)
            if (result.success == false) {
                albumListApp.imgList.length = 0
                $(".imgList").hidden()
                $(".photoShowGallery").append("<span class='emptyAlbum'>相册为空</span>")
            } else {
                if(result.data.length!=0){
                    $(".imgList").show()
                    $(".emptyAlbum").remove();
                    albumListApp.imgList = result.data;
                    // for(let i=0;i<result.data.length;i++){
                    //     albumListApp.imgList.push();
                    // }
                }else {
                    $(".imgList").remove()
                    albumListApp.imgList.length = 0
                    $(".photoShowGallery").append("<span class='emptyAlbum'>相册为空</span>")
                    $(".imgList").hide()
                }
            }
        },
        error: function (result) {
            //alert("系统繁忙!");
        }
    });
}

function showPhotoDetail(index) {
    albumListApp.activePhoto = index;
    //模板引擎渲染轮播图
    $(".swiperWrapper").css("display", "block");
    $(".imgListWrapper").html(
        template("swiperTemplate", {
            list: albumListApp.imgList
        })
    );
    //轮播图
    var galleryThumbs = new Swiper('.gallery-thumbs', {
        spaceBetween: 10,
        slidesPerView: 7,
        freeMode: true,
        watchSlidesVisibility: true,
        watchSlidesProgress: true
    });
    var galleryTop = new Swiper('.gallery-top', {
        keyboard: true,
        spaceBetween: 10,
        initialSlide: albumListApp.activePhoto, //设定初始化时slide的索引
        navigation: {
            nextEl: '.swiper-button-next',
            prevEl: '.swiper-button-prev'
        },
        pagination: {
            el: '.swiper-pagination',
            type: 'fraction'
        },
        thumbs: {
            swiper: galleryThumbs
        },
        observer: true,//修改swiper自己或子元素时，自动初始化swiper
        observeParents: true,//修改swiper的父元素时，自动初始化swiper,
        on: {
            init: function () { //Swiper初始化时，赋值照片信息展示区域
                console.log(123)
                albumListApp.activePhotoInfo = albumListApp.imgList[this.activeIndex];
                currentShowImageInfo = albumListApp.imgList[this.activeIndex];
                showRemark(currentShowImageInfo.fileid);
            },
            slideChangeTransitionEnd: function () { //切换结束时，修改照片信息展示区域
                console.log(456)
                albumListApp.activePhotoInfo = albumListApp.imgList[this.activeIndex];
                currentShowImageInfo = albumListApp.imgList[this.activeIndex];
                showRemark(currentShowImageInfo.fileid);
            },
        },
    });
    // 监听退出按钮
    $(document).on("click", ".exitButton", function () {
        $(".swiperWrapper").css("display", "none");
        $("#navbottomBarId").show()
    });

    $("#navbottomBarId").hide()
}
/**
 * 冒泡事件处理
 * @param param
 */
function handleSelectIcon(param) {
    if ($(".selectIcon")[param].innerText != "") {   //选中框内添加√
        $(".selectIcon")[param].innerText = "";
        $(".selectIcon")[param].classList.remove("selected");
    } else {
        $(".selectIcon")[param].innerText = "√";
        $(".selectIcon")[param].classList.add("selected");
    }
    if ($(".selected").length == $(".selectIcon").length) {
        $("#selectAll").text("取消全选");
        $("#selectAll").addClass("cancelSelectAll");
    }
}

/**
 * 向右旋转图片 90度
 * @param imageid
 */
function totationImage(imageid) {
    var imageInfo = {
        direction: "right",
        imageid: imageid
    };
    $.ajax({
        data: imageInfo,
        url: "/filetransfer/totationimage",
        dataType: "json",
        type: "POST",
        async: true,
        success: function (result) {
            if (result.success) {
                albumListApp.initAlbum();
                albumListApp.showPhotoDetail(albumListApp.activePhoto);
            } else {
                alert(result.errorMessage);
            }
        },
        error: function () {
            //alert("系统繁忙!");
        }
    });
}

/**
 * 删除图片
 * @param imagePath 图片路径
 * @param imageid 图片id
 * @param activePhotoIndex
 */
function deletePhoto(imagePath, imageid, activePhotoIndex) {
    var imageInfo = {
        imageurl: imagePath,
        imageid: imageid
    };
    $.ajax({
        data: imageInfo,
        url: "/filetransfer/deleteimage",
        dataType: "json",
        type: "POST",
        async: true,
        success: function (result) {
            if (result.success) {
                layer.msg("删除成功", {icon: 1})
                // 关闭轮播图，照片列表中删除相应元素
                $(".swiperWrapper").css("display", "none");
                $(".imgList").children(".list-item")[activePhotoIndex].style.display = "none";
            } else {
                layer.msg(result.errorMessage, {icon: 2})
            }
        },
        error: function () {
            //alert("系统繁忙!");
        }
    });
}

function updatePhotoCount(fileid) {
    var imageInfo = {
        fileid: fileid
    };
    $.ajax({
        data: imageInfo,
        url: "/file/primarirycount",
        dataType: "json",
        type: "POST",
        async: true,
        success: function (result) {
            if (result.success) {
                layer.msg("点赞成功", {icon: 1})
                // window.location.reload()
                $(".exitButton").click()
            } else {
                layer.msg(result.errorMessage, {icon: 2})
            }
        },
        error: function () {
            //alert("系统繁忙!");
        }
    });
}

function deleteCurrentImage() {
    var imagePath = document.getElementsByClassName("ma5-clone")[0].getAttribute("src");
    var id = document.getElementsByClassName("ma5-clone")[0].getAttribute("id");

    var imageInfo = {
        fileurl: imagePath,
        fileid: id
    };
    $.ajax({
        data: imageInfo,
        url: "/filetransfer/deleteimage",
        dataType: "json",
        type: "POST",
        async: true,
        success: function (result) {
            if (result.success) {
                layer.msg("删除成功", {icon: 1})
                window.location.href = "showalbum.html?albumId=" + albumId;
            } else {
                layer.msg(result.errorMessage, {icon: 2})
            }
        },
        error: function () {
            //alert("系统繁忙!");
        }
    });
}

//添加评论
function remarkConfirm() {
    var remarkContent = document.getElementById("remarkInputId").value;
    if (remarkContent.trim() == "") {
        alert("内容为空");
    }
    if (!currentShowImageInfo) {
        currentShowImageInfo = albumListApp.imgList[0];
    }
    var essayJson = {};
    essayJson["targetid"] = currentShowImageInfo.fileid;
    essayJson["remarkContent"] = remarkContent;
    essayJson["modulename"] = "album";

    $.ajax({
        data: essayJson,
        url: "/remark/addremark",
        dataType: "json",
        type: "POST",
        success: function (result) {
            if (result.success) {
                showRemark(currentShowImageInfo.fileid);
                document.getElementById("remarkInputId").value = ""
            } else {
                alert(result.errorMessage);
            }
        },
        error: function (result) {
            alert("系统繁忙!");
        }
    });
}

//显示评论内容
function showRemark(fileid) {
    var essayJson = {};
    essayJson["targetid"] = fileid;
    essayJson["modulename"] = "album";
    $.ajax({
        data: essayJson,
        url: "/remark/getremarkcontent",
        dataType: "json",
        type: "get",
        success: function (result) {
            if (result.success) {
                albumListApp.remarkList = result.data;

            } else {
                alert(result.errorMessage);
            }
        },
        error: function (result) {
            //alert("系统繁忙!");
        }
    });

}


function clickReply(remarkInfo) {
    var username;
    var userId;
    var remarkedId;
    if (remarkInfo.essayId != null) {
        username = remarkInfo.userBean.username;
        userId = remarkInfo.userBean.userId;
        remarkedId = remarkInfo.remarkId;
    } else {
        username = remarkInfo.repliedUserName;
        userId = remarkInfo.repliedUserId;
        remarkedId = remarkInfo.remarkedId;
    }
    var repliedUserObj = {};
    repliedUserObj["repliedUserId"] = userId;
    repliedUserObj["repliedUserName"] = username;
    repliedUserObj["remarkedId"] = remarkedId;
    layer.prompt({
        formType: 2,
        placehold: "回复" + username,
        title: '回复',
        area: ['420px', '200px'] //自定义文本域宽高
    }, function (value, index, elem) {

        if (value.trim() == "") {
            // alert("内容为空");
            layer.msg("内容为空", {icon: 2})
        } else {
            repliedUserObj["replyContent"] = value;
            $.ajax({
                data: repliedUserObj,
                url: "/remark/addreply",
                dataType: "json",
                type: "POST",
                success: function (result) {
                    if (result.success) {
                        layer.msg("成功", {icon: 1})
                        showRemark(currentShowImageInfo.fileid)
                    } else {
                        layer.msg(result.errorMessage, {icon: 2})
                    }
                },
                error: function (result) {
                    layer.msg("系统繁忙", {icon: 2})
                }
            });
        }

        layer.close(index);
    });

}

// function divWidth(className){
//     console.log(className)
//     $("."+className).width(document.body.clientWidth)
// }
// window.onresize = function(){
//     divWidth('swiperWrapper')
// }
